from flask import Blueprint, request,redirect,url_for
from common.libs.Helper import ops_renderJSON, iPagenation, ops_render
from common.models.template import Template
from application import db, app
from common.libs.DataHelper import getCurrentTime
import flask_excel as excel
from qiniu import Auth
from qiniu import put_data
from qiniu import BucketManager
import os

template_page = Blueprint("template_page", __name__)


# 详情页展示
@template_page.route('/template', methods=['GET', 'POST'])
def template():
    classone = ["招标模板", "承建商模板", "合同模板"]
    num = []
    for item in classone:
        datanum = Template.query.filter_by(classone=item,mark=1).count()
        num.append(datanum)

    alldetail = []
    for item in classone:
        template = Template.query.filter_by(classone=item,mark=1).all()
        alldetail.append(template)

    return ops_render("/template/template.html",
                      {"alldetail": alldetail,"num": num})


# 上传文件
@template_page.route('/upload', methods=['GET', 'POST'])
def uploadfile():
    # 从前端获取文件
    f = request.files.getlist('files')
    classone = request.form.get('classone')
    uid = request.form.get('uid')


    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'library-filestore'
    # http://+外链域名
    domian_name = 'http://libraryfilestore.guanzhuoran.cn/'
    # 生成上传 Token，可以指定过期时间等

    for item in f:
        name = item.filename
        file = item.read()
        uploadname = classone + "-" + name

        name, type1 = os.path.splitext(name)
        type = type1.replace(".", "")
        size = len(file) / 1000000
        size = round(size, 2)

        url = domian_name + uploadname
        token = q.upload_token(bucket_name, uploadname, 3600)

        ret, info = put_data(token, uploadname, data=file)

        template = Template()
        template.type = type
        template.size = size
        template.url = url
        template.mark = 1
        template.uid = uid
        template.classtwo = name
        template.classone = classone
        template.created_time = template.updated_time = getCurrentTime()
        db.session.add(template)
        db.session.commit()


    return ops_renderJSON(msg="上传成功")







@template_page.route('/detaildelete', methods=['GET', 'POST'])
def deletedetail():
    id = request.args.get('id')
    detail = Template.query.filter_by(id=id).first()
    classone = str(detail.classone)
    classtwo = str(detail.classtwo)
    type = str(detail.type)

    uploadname= classone+"-"+classtwo+"."+type

    access_key = 'po98t2WFtFrNvPJ_bZTFobndhhKhQUk6mrXq2NX1'
    secret_key = 'DbooW85jje3wtiDP0se_JLL76PjgLGc-3p2fiEaZ'
    # 初始化Auth状态
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    bucket_name = 'library-filestore'
    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, uploadname)
    if info.status_code == 200:
        template = Template.query.filter_by(id=id).first()
        template.mark = 0
        db.session.commit()
        return redirect(url_for('template_page.template'))
    else:
        return ops_renderJSON(msg="删除失败")